var records = [];
var ctxPath = $('body').attr('ctxPath');
var blackBoxDlgIndex;
var blackBoxDlg = $('#blackBoxDlg');
var chart1;
var chart2;
var chart3;
var chart4;
var flag = false;
var count = 0;

/**
 * 毫秒值转日期 yyyy-MM-dd HH:mm:dd
 */
function dateFormat(ms) {
    var date = new Date(ms);
    var y = date.getFullYear();
    var mon = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return y + '-' + mon + '-' + d + ' ' + h + ':' + min + ':' + s;
}


/**
 * 毫秒值转时间 HH:mm
 */
function timeFormat(ms) {
    var date = new Date(ms);
    var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var min = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    return  h + ':' + min ;
}



/**
 * 获取最近20分钟时间
 */
var getNowTime = function () {
    var date = new Date();
    //拿到当前的毫秒值
    var milliseconds  = date.getTime();
    var time ;
    var times = [];
    for ( var i = -19 ; i < 1 ; i ++ ){
        time = milliseconds + (1000 * 60 * i);
        times.push(timeFormat(time));
    }

    //console.log(times);
    return times;

}



$(function () {


    $.ajax({
        'url': ctxPath + '/curve/before/data?_t=' + new Date().getTime(),
        'type': 'post',
        'dataType': 'json',
        'success': function (res) {
            if (res.statusCode == 200) {
                var second = res.data.second;
                var one = res.data.one;
                var two = res.data.two;
                var three = res.data.three;
                var four = res.data.four;
                //数据接收展示
                chart1 = echarts.init(document.getElementById('quxian'), 'dark')
                var option1 = {
                    title: {
                        text: '优化曲线'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        bottom: '3%',
                        textStyle: {
                            color: '#fff',
                        },
                        data: ['1#电池堆', '2#电池堆', '3#电池堆', '4#电池堆']
                    },

                    xAxis: [{
                        type: 'category',
                        boundaryGap: false,
                        splitLine: {
                            show: false
                        },
                        data: getNowTime(),
                    }],
                    yAxis: [{
                        type: 'value',
                        splitLine: {
                            show: false
                        },
                        min: function (value) {
                            return value.min - 0.03;
                        },
                        max: function (value) {
                            return value.max + 0.03;
                        }
                    }],
                    series: [{
                        symbol: "none",
                        name: '1#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(255,0,0)',
                        data: one
                    }, {
                        symbol: "none",
                        name: '2#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(0,255,0)',
                        data: two
                    }, {
                        symbol: "none",
                        name: '3#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(0,0,255)',
                        data: three
                    }, {
                        symbol: "none",
                        name: '4#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(255,255,0)',
                        data: four
                    }]
                };

                chart1.setOption(option1);
            }
        },
        'error': function (err) {

        }
    })


    /**
     * 10s获取一次最新的数据,
     */
    setInterval(function () {
        ++count ;
        console.log(count,flag);
        $.ajax({
            'url': ctxPath + '/curve/before/data?_t=' + new Date().getTime(),
            'type': 'post',
            'data':{'count':count,'flag':flag},
            'dataType': 'json',
            'success': function (res) {
                var second = res.data.second;
                var one = res.data.one;
                var two = res.data.two;
                var three = res.data.three;
                var four = res.data.four;
                chart1.setOption({
                    xAxis: {
                        data: getNowTime(),
                    },
                    series: [{
                        symbol: "none",
                        name: '1#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(255,0,0)',
                        data: one
                    }, {
                        symbol: "none",
                        name: '2#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(0,255,0)',
                        data: two
                    }, {
                        symbol: "none",
                        name: '3#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(0,0,255)',
                        data: three
                    }, {
                        symbol: "none",
                        name: '4#电池堆',
                        type: 'line',
                        smooth: 0.5,
                        symbolSize: 8,
                        color: 'rgb(255,255,0)',
                        data: four
                    }]

                });
            },
            'error':function (err) {

            }
        })


    },500)






    /**
     * 建立Socket链接
     */
    webSocketInit();

    /**
     * 表格数据实时更新
     */
    function webSocketInit() {
        if ("WebSocket" in window) {
            console.log("您的浏览器支持 WebSocket!");

            // 打开一个 web socket
            var ws = new WebSocket("ws://" + document.domain + ctxPath + "/socket/1/2");

            // Web Socket 连接建立时触发，使用 send() 方法发送数据
            ws.onopen = function () {
                //ws.send("这条消息是有前端通过websocket发送的");
                console.log('WebSocket链接建立成功');
                layer.msg("Socket 通信已连接");
            };

            //前端接收到服务端数据时触发
            ws.onmessage = function (evt) {

                //有数据下发时,标识符修改为true;
                flag = true;

                $('#tbl').empty();
                console.log("接收到服务器数据", evt);
                var received_msg = evt.data;
                records = eval("(" + received_msg + ")");
                //console.log(records);
                for (var i = 0, len = records.length; i < len; i++) {
                    //最新的下发时间更新
                    if (i == 0) {
                        $('#pushTime').text(dateFormat(records[i].operateTime));
                    }
                    var tr = $("<tr/>");
                    var td1 = $("<td/>");
                    var td2 = $("<td/>");
                    var td3 = $("<td/>");
                    var td4 = $("<td/>");
                    td1.append(i + 1);
                    td2.append(dateFormat(records[i].operateTime));
                    td3.append(records[i].type)
                    td4.append(records[i].status)
                    tr.append(td1).append(td2).append(td3).append(td4);
                    //console.log(records[i]);
                    $('#tbl').append(tr);
                }
            };

            //通信出错时触发
            ws.onerror = function (err) {
                layer.alert("建立Socket 通信出错", err)
            }

            //链接关闭时触发
            ws.onclose = function () {
                // 关闭 websocket
                //layer.alert("WebSocket连接已关闭!");
                layer.alert('Socket 通信已断开 <br/> 请刷新尝试重连')
            };
        } else {
            // 浏览器不支持 WebSocket
            layer.alert("您的浏览器不支持 WebSocket");
        }
    }


    window.addEventListener("resize", function () {
        chart1.resize();
    });

    $('#heixiazi').on('click', function () {
        console.log('演示黑匣子功能');
        //点击黑匣子演示,定时器完成后新增一条黑匣子记录

        setTimeout(function () {
            $.ajax({
                'url': ctxPath + '/black/box/add?_t=' + new Date().getTime(),
                'type': 'post',
                'dataTyp': 'json',
                'success': function (res) {
                    //console.log(res)
                    if (res.statusCode == 200) {

                        $('#recordText').text('黑匣子记录（' + res.data.createTime + '）');
                        $('#recordTime').text(res.data.createTime);
                        layer.alert('2#电池堆温升过快<br/>黑匣子功能已启动！');
                        $('#blackBoxRecord').show();
                    }
                },
                'error': function (err) {

                }
            })


        }, 1000)
    })

    /**
     * 点击查看
     */
    $('#viewRecord').on('click', function () {
        $.ajax({
            'url': ctxPath + '/look/box/data?_t=' + new Date().getTime(),
            'type': 'post',
            'dataType': 'json',
            'success': function (res) {
                console.log(res);
                if (res.statusCode == 200) {
                    var second = res.data.second;
                    var v = res.data.v;
                    var i = res.data.i;
                    var t = res.data.t;

                    chart2 = echarts.init(document.getElementById('dianYa'), 'dark');
                    chart3 = echarts.init(document.getElementById('dianLiu'), 'dark');
                    chart4 = echarts.init(document.getElementById('wenDu'), 'dark');

                    var option2 = {
                        title: {
                            text: '电\n压\n变\n化\n曲\n线',
                            textStyle: {
                                fontSize: 13
                            },
                            top: 55,
                            left: 15
                        },
                        backgroundColor: 'rgb(35,37,49)',
                        xAxis: {
                            type: 'category',
                            data: second
                        },
                        yAxis: {
                            splitLine: {
                                show: false
                            },
                            type: 'value',
                            min: function (value) {
                                return value.min - 10;
                            },
                            max: function (value) {
                                return value.max + 10;
                            }
                        },
                        series: [{
                            color: 'rgb(182,149,73)',
                            data: v,
                            type: 'line'
                        }]
                    };

                    var option3 = {
                        title: {
                            text: '电\n流\n变\n化\n曲\n线',
                            textStyle: {
                                fontSize: 13
                            },
                            top: 55,
                            left: 15
                        },
                        backgroundColor: 'rgb(35,37,49)',
                        xAxis: {
                            type: 'category',
                            data: second
                        },
                        yAxis: {
                            splitLine: {
                                show: false
                            },
                            type: 'value',
                            min: function (value) {
                                return value.min - 10;
                            },
                            max: function (value) {
                                return value.max + 10;
                            }
                        },
                        series: [{
                            color: 'rgb(182,149,73)',
                            data: i,
                            type: 'line'
                        }]
                    };

                    var option4 = {
                        title: {
                            text: '温\n度\n变\n化\n曲\n线',
                            textStyle: {
                                fontSize: 13
                            },
                            top: 55,
                            left: 15
                        },
                        backgroundColor: 'rgb(35,37,49)',
                        xAxis: {
                            type: 'category',
                            data: second
                        },
                        yAxis: {
                            splitLine: {
                                show: false
                            },
                            type: 'value',
                            min: function (value) {
                                return value.min - 10;
                            },
                            max: function (value) {
                                return value.max + 10;
                            }
                        },
                        series: [{
                            color: 'rgb(182,149,73)',
                            data: t,
                            type: 'line'
                        }]
                    };

                    chart2.setOption(option2);
                    chart3.setOption(option3);
                    chart4.setOption(option4);

                    var title = $('#recordText').text();
                    blackBoxDlgIndex = layer.open({
                        title: title,
                        type: 1,
                        area: ['1300px', '750px'], //宽高
                        content: blackBoxDlg
                    })
                }

            },
            'error': function (err) {
                layer.alert('网络异常')
            }
        })


    })

    window.addEventListener("resize", function () {
        if (chart1) {
            chart1.resize();
        }
        if (chart2) {
            chart2.resize();
        }
        if (chart3) {
            chart3.resize();
        }
        if (chart4) {
            chart4.resize();
        }

    });


})
